package com.fr71.project.dm.listener;

import com.fr71.common.utils.DateUtils;
import com.fr71.common.utils.spring.SpringUtils;
import com.fr71.project.dm.domain.PdUser;
import com.fr71.project.dm.service.IPdUserService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class AuthUtil {
    private static final Logger logger = LoggerFactory.getLogger(AuthUtil.class);

    private static final ConcurrentHashMap<String, ChannelHandlerContext> channels = new ConcurrentHashMap<>();

    private static IPdUserService iPdUserService;

    static {
        iPdUserService = SpringUtils.getBean(IPdUserService.class);
    }

    public static String getRemoteAddr(ChannelHandlerContext ctx) {
        return ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
    }

    public static void noticeClient(String ip) {
        if (ip == null || ip.isEmpty()) return;
        ChannelHandlerContext ctx = channels.get(ip);
        if (ctx != null) {
            ctx.channel().writeAndFlush(new TcpDataWriter(1).get());
        }
    }

    public static void addChannel(ChannelHandlerContext ctx) {
        String ip = getRemoteAddr(ctx);
        if (channels.containsKey(ip)) {
            ctx.close();
        }
        channels.put(ip, ctx);
        //更新这个ip的数据
        PdUser queryUser = new PdUser();
        queryUser.setBindIp(ip);
        queryUser.setUType(1);
        List<PdUser> userList = iPdUserService.selectPdUserList(queryUser);
        for (PdUser it : userList) {
            it.setLastConnectTime(DateUtils.getNowDate());
            it.setOnlines("Y");
            iPdUserService.updatePdUser(it);
        }
        logger.debug("链接数量:" + channels.size());
    }

    public static void removeChannel(ChannelHandlerContext ctx) {
        String key = getRemoteAddr(ctx);
        if (channels.containsKey(key)) {
            ctx.close();
            channels.remove(key);
            //更新这个ip的数据
            PdUser queryUser = new PdUser();
            queryUser.setBindIp(key);
            queryUser.setUType(1);
            List<PdUser> userList = iPdUserService.selectPdUserList(queryUser);
            for (PdUser it : userList) {
                it.setLastDisConnectTime(DateUtils.getNowDate());
                //计算累计使用时长
                it.setTotalUsedTime(it.getTotalUsedTime() + it.getLastDisConnectTime().getTime() - it.getLastConnectTime().getTime());
                it.setOnlines("N");
                iPdUserService.updatePdUser(it);
            }
        }
        logger.debug("链接数量:" + channels.size());
    }
}